package com.wcs.exam.common.base;

import cn.hutool.extra.servlet.JakartaServletUtil;
import com.wcs.exam.common.base.page.SqlUtil;
import com.wcs.exam.common.cache.CacheCount;
import com.wcs.exam.common.cache.CacheRedis;
import com.wcs.exam.common.util.IpUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 基础类
 *
 * @author wcs
 */
@Slf4j
public class BaseBiz {

    @Resource
    protected HttpServletRequest request;
    @Resource
    protected HttpServletResponse response;
    @Resource
    protected CacheRedis cacheRedis;
    @Resource
    protected CacheCount cacheCount;
    @Resource
    protected NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    /**
     * response 不进行缓存配置
     */
    protected void setNoCache() {
        response.setHeader("Cache-Control", "no-cache");
    }

    protected String getClientIP() {
        return JakartaServletUtil.getClientIP(request);
    }

    protected IpUtil.IpInfo getIpInfo(String ip) {
        IpUtil.IpInfo ipInfo = cacheRedis.get(ip, IpUtil.IpInfo.class);
        if (ipInfo == null) {
            ipInfo = IpUtil.getIpInfo(ip);
            if (ipInfo != null) {
                cacheRedis.set(ip, ipInfo, 1, TimeUnit.DAYS);
            }
        }
        return ipInfo;
    }

    /**
     * 获取当前语言的国际化信息
     *
     * @param code 编码
     * @return 提示信息
     */
    public String toI18n(String code) {
        return code;
    }

    /**
     * 操作成功
     *
     * @return 操作成功提示信息
     */
    public String toI18nSuccess() {
        return "操作成功";
    }

    /**
     * 操作失败
     *
     * @return 操作失败提示信息
     */
    public String toI18nFail() {
        return "操作失败";
    }

    protected int sort(List<SortReq> sorts, String tableName) {
        tableName = SqlUtil.camelToUnderscore(tableName);
        String sql = "update TABLENAME set sort = :sort where id = :id".replace("TABLENAME", tableName);
        return this.namedParameterJdbcTemplate.batchUpdate(sql, SqlParameterSourceUtils.createBatch(sorts)).length;
    }

}
